package com.copa.gameStore.service.impl;

import com.copa.gameStore.client.UserClient;
import com.copa.gameStore.domain.AuthenticUser;
import com.copa.gameStore.domain.User;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author copa
 * @createDate 2022-10-20 10:09
 * @function 认证用户信息查询服务
 */
@Service
public class AuthenticUserDetailService implements UserDetailsService {

    @Resource
    private UserClient userClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = Optional.ofNullable(userClient.findByUsername(username)).orElseThrow(() -> new UsernameNotFoundException("用户名或密码错误!"));
        List<String> roleNameList = userClient.roleNameByUserId(user.getId());

        if (user.getIsEnable()) {
            throw new DisabledException("该账户已被禁用，请联系管理员!");
        } else if (user.getIsLock()) {
            throw new LockedException("该账号已被锁定，请联系管理员!");
        } else if (user.getIsExpire()) {
            throw new AccountExpiredException("该账号已过期，请联系管理员!");
        } else if (user.getPasswordExpire()) {
            throw new CredentialsExpiredException("没有访问权限，请联系管理员!");
        }
        return new AuthenticUser(user, roleNameList);
    }


}
